angular.module('app')
    .controller('updateScenesController', ['$scope', '$rootScope', '$state', '$timeout',
        function($scope, $rootScope, $state, $timeout) {
            var title = "编辑";
            var id = $state.params.id;
            var scenesType = $state.params.scenesType;
            $scope.title = $rootScope.title = title;
            $scope.loading = true;
            $scope.mediaId={};
            $scope.scenesType=scenesType;
            $scope.record1={};
            // 分页
            $scope.pagingData = {
                'total': 2,
                'currentPage': 0,
                'paginLength': 6,
                'pageSize': '10'
            };

            // 广告位查询按钮
            $scope.queryMedia = function (val) {
                // $scope.mediaList=[]
                if (val == 'query') {
                    $scope.pagingData.currentPage = 0
                }
                $scope.inquire(val)
            }

            $scope.allclear=function () {
                // $scope.record1.records={};
                $scope.alertMessage({
                    text:"确定做此操作吗？", //内容
                    btnCancel:true, //取消按钮
                    btnConfirm:true //确认按钮
                }).then(function () {
                    $scope.record1.records={};
                    $scope.$apply();
                })

            }
            var onoff = false;
            $scope.inquire = function (val) {
                $scope.param= {};
                // $scope.mediaName='';
                // $scope.platformName='';
                // $scope.slotSize='';
                // $scope.flowType='';
                // alert($scope.adMedia);
                var mediaName=$("#mediaName").val();
                var platformName=$("#platformName").val();
                var slotSize=$("#slotSize").val();
                var flowType=$("#flowType").val();
                var mediaId='0';
                angular.forEach($scope.showMedia, function(value, key) {
                    mediaId=mediaId+','+value.id;
                });
                var id=mediaId;
                if(mediaId.length>2){
                    id=id.substring(2);
                }else {
                    id='';
                }
                console.log(id);
                //  广告位查询接口
                $.ajax({
                    url : $scope.app.project_name+'/scenesPackage/getMediaList',
                        data: {'mediaIdNotIn': id,'pageNum':$scope.pagingData.currentPage,'mediaName':mediaName,'platformName':platformName,'slotSize':slotSize,'flowType':flowType}
                }).then(function(result) {
                    console.log(result);
                    $scope.loading = false;
                    if (result.httpCode == 200) {
                        $scope.pagingData.total = result.data.total;
                        $scope.copyMedia(result.data.records, val);
                        // $scope.record = result.data;

                    } else {
                        $scope.msg = result.msg;
                    }
                    $scope.$apply();
                });
            }
            // 场景包广告位 删除按钮
            $scope.deleteEditor = function (id) {
                $scope.alertModel({
                    text: '是否确定删除？',
                    resCode: '00001',
                    btnCancel: true
                }).then(function () {
                    $scope.$apply(function () {
                        $scope.showMedia.forEach(function (t,index) {
                            if(t.id==id){
                                $scope.showMedia[index].isChecked = false
                                var a= $scope.showMedia.splice(index, 1)[0]
                            }
                        })
                        $scope.deduplication()   // 调用的去重方法
                    })
                })
            }

            // 单选
            $scope.singleCheck = function (val) {
                $scope.selectAll = false;
            }
            // 全选功能
            $scope.checkedAll = function () {
                for (var i = 0; i < $scope.dedupList.length; i++) {
                    if ($scope.selectAll) {
                        $scope.dedupList[i].isChecked = true;
                    } else {
                        $scope.dedupList[i].isChecked = false;
                    }
                }
            };

            // 场景包广告位 清空按钮
            $scope.deleteAll = function () {
                $scope.alertModel({
                    text: '是否确定清空？',
                    resCode: '00001',
                    btnCancel: true
                }).then(function () {
                    $scope.$apply(function () {
                        $scope.showMedia.forEach(function (item) {
                            item.isChecked = false
                        })
                        $scope.showMedia = []
                        $scope.deduplication()   // 调用的去重方法
                        // Array.prototype.push.apply($scope.deleteAllArr, $scope.showMedia) // 合并两个数组
                    })
                })
            }
            // 获取勾选列表的id的数组
            $scope.getAdSlotId = function () {
                $scope.adSlotIds = [];
                $scope.adMedia = [];
                if (!$scope.mediaList) {
                } else {
                    for (var i = 0; i < $scope.dedupList.length; i++) {
                        if ($scope.dedupList[i].isChecked) {
                            $scope.adSlotIds.push($scope.dedupList[i].id);
                            $scope.adMedia.push($scope.dedupList[i]);
                            // $scope.mediaList.splice(i,1)
                        }
                    }
                }
            };

            // 增加场景包中的广告位
            $scope.addArr = function () {
                $scope.getAdSlotId();
                // if (!$scope.showMedia) {
                //   $scope.showMedia = []
                // }
                for (var i = 0; i < $scope.adMedia.length; i++) {
                    $scope.showMedia.push($scope.adMedia[i])
                }
                $scope.isShow = !$scope.isShow
                $scope.deduplication()   // 调用的去重方法
                $('#chongz').modal('hide');
            }

            // 场景包中广告位分页功能
            $scope.showMedia = []

            // 场景包广告位分页
            $scope.pagingData2 = {
                'total': 2,
                'currentPage': '1',
                'paginLength': 6,
                'pageSize': '5'
            };
            $scope.$watch('showMedia', function (v) {
                $scope.pagingData2.total = v.length
                $scope.goTo($scope.pagingData2)
            }, true)
            $scope.goTo = function (data) {
                var index = (data.currentPage - 1) * data.pageSize
                $scope.copyShowMedia = $scope.showMedia.slice(index, index + data.pageSize)
            }


            $scope.mediaList = [];
            // copy数组
            $scope.copyMedia = function (list, val) {
                if (val == 'query') {
                    $scope.mediaList = list;
                    $scope.query = true
                } else {
                    if ($scope.query) {
                        $scope.mediaList = []
                        $scope.query = false
                    }
                    var obj;
                    for (var i = 0; i < list.length; i++) {
                        obj = {};
                        obj.dayShowVolume = list[i].dayShowVolume;
                        obj.flowType = list[i].flowType;
                        obj.id = list[i].id;
                        obj.mediaName = list[i].mediaName;
                        obj.slotName = list[i].slotName;
                        obj.slotType = list[i].slotType;
                        obj.platformName = list[i].platformName;
                        obj.slotSize = list[i].slotSize;
                        obj.isChecked = false;
                        $scope.mediaList.push(obj);
                    }
                }
                $scope.deduplication()   // 调用的去重方法
            }
            // 场景包中的已选广告位，查询广告位时不显示
            $scope.deduplication = function () {
                function c(o) {
                    return $scope.showMedia.some(function (v) {  // 数组去重
                        return v.id === o.id
                    })
                }

                $scope.dedupList = $scope.mediaList.filter(function (o) {
                    return !c(o)
                })

            }



            $scope.dedupList = []
            $scope.add = function() {
                $('#chongz').modal('show',true);
                $scope.queryDate()
            }

            $scope.saveRecharge = function() {
                // var mediaId='0';
                // $('input[name="checkpig"]:checked').each(function(){
                //     var sfruit=$(this).val();
                //     mediaId=mediaId+','+sfruit;
                //
                // });
                // angular.forEach($scope.record1.records, function(value, key) {
                //     mediaId=mediaId+','+value.id;
                // });
                //
                // var id=mediaId;
                // $scope.mediaId=mediaId;
                //
                // $.ajax({
                //     url : $scope.app.project_name+'/scenesPackage/getMediaList',
                //     data: {'mediaId': id}
                // }).then(function(result) {
                //     $scope.loading = false;
                //     if (result.httpCode == 200) {
                //         $scope.record1 = result.data;
                //         $('#chongz').modal('hide');
                //     } else {
                //         $scope.msg = result.msg;
                //     }
                //     $scope.$apply();
                // });

            }

            $scope.delRecharge=function (id) {

                $scope.alertMessage({
                    text:"确定做此操作吗？", //内容
                    btnCancel:true, //取消按钮
                    btnConfirm:true //确认按钮
                }).then(function () {
                    angular.forEach($scope.record1.records, function(data,index,array){
                        if(data.id==id){
                            $scope.record1.records.splice(index,1);
                        }
                    });
                    $scope.$apply();
                })

            }


            $scope.queryDate = function (isScroll) {//请求分页
                if ($scope.pagingData.currentPage >= Math.ceil($scope.pagingData.total / $scope.pagingData.pageSize)) {
                    return
                    // $scope.dedupList = []
                } else {
                    if (isScroll) {
                        $scope.pagingData.currentPage += 1
                        $scope.inquire()
                    } else if ($scope.dedupList.length / $scope.pagingData.pageSize < 1) {
                        $scope.pagingData.currentPage += 1
                        $scope.inquire()
                    }
                }
            }

            // 滚动条下拉分页获取数据
            var top = document.querySelector('#top')
            var elementTop = angular.element(top)
            var timer = null;
            elementTop.scroll(function () {
                var scrollNum = elementTop.scrollTop() // 滚动条滚动距离
                var scrollH = elementTop[0].scrollHeight; // 滚动条高度
                var offsetH = elementTop[0].offsetHeight;  // 可视高度
                if (scrollNum + offsetH == scrollH && !onoff) {  // 判断
                    clearTimeout(timer)
                    onoff = true
                    timer = setTimeout(function () {
                        onoff = false
                    }, 1000);
                    $scope.queryDate(true)
                }
            })


            $scope.save = function(sid,userIdS) {
                var scenesType=$scope.scenesType;
                // var userIdS=$scope.userIdS
                var company=$("#company").val();
                var scenesName=$("#scenesName").val();
                // var searchParams=$("#searchParams").val();
                var activeName=$("#activeName").val();
                var activeLink=$("#activeLink").val();
                var content=$("#content").val();
                var mediaId='0';
                // angular.forEach($scope.record1.records, function(data,index,array){
                //     mediaId=mediaId+","+data.id;
                //     falg=false;
                // });
                angular.forEach($scope.showMedia, function(value, key) {
                    mediaId=mediaId+','+value.id;
                });
                // alert(mediaId);
                if(mediaId.length>2){
                    mediaId=mediaId.substring(2);
                }else {
                    mediaId='';
                }
                if(scenesType==null || scenesType==''){
                    alert("场景包类型不能为空！");
                    // $scope.alertModal({"content":"场景包类型不能为空！"});
                    return;
                }
                if(company==null || company=='' || company==undefined){
                    // $scope.alertModal({"content":"所属公司名称不能为空！"});
                    alert("所属公司名称不能为空！");
                    return;
                }
                if(scenesName==null || scenesName==''){
                    // $scope.alertModal({"content":"场景包名称不能为空！"});
                    alert("场景包名称不能为空！");
                    return;
                }
                if(scenesName.length>20){
                    // $scope.alertModal({"content":"场景包名称最大长度20"});
                    alert("场景包名称最大长度20");
                    return;
                }
                if(activeName.length>10){
                    // $scope.alertModal({"content":"支持活动名称最大长度10"});
                    alert("支持活动名称最大长度10");
                    return;
                }
                if(content.length>120){
                    // $scope.alertModal({"content":"说明最大长度120"});
                    alert("说明最大长度120");
                    return;
                }
                if(mediaId.length=='0'){
                    // $scope.alertModal({"content":"场景包广告位不能为空！"});
                    alert("场景包广告位不能为空！");
                    return;
                }

                $.ajax({
                    //调用修改接口
                    url : $scope.app.project_name+'/scenesPackage/editMediaSlotBean',
                    data: {'scenesName': scenesName,'scenesType': scenesType,'company': company,'activeName': activeName,'activeLink': activeLink,'content': content,'mediaId': mediaId,'id':sid,'userIdS':userIdS}
                }).then(function(result) {
                    $scope.loading = false;
                    if (result.httpCode == 200) {
                        // alert("保存成功");
                        $state.go('main.toolChest.scenes.readList');
                    } else {
                        $scope.msg = result.msg;
                    }
                    $scope.$apply();
                });
            }


            $scope.isSelected = function(id){
                var falg=false;
                angular.forEach($scope.record1.records, function(value, key) {
                    if(value.id==id){
                        falg=true;
                        return falg;
                    }
                });
                return falg;
            }
            activate(id,scenesType);
            // 初始化页面
            function activate(id,scenesType) {
                $scope.loading = true;
                // alert(scenesType);
                $.ajax({
                    url : $scope.app.project_name+'/scenesPackage/delitToolManageCrt',
                    data: {'id': id}
                }).then(function(result) {
                    $scope.loading = false;
                    if (result.httpCode == 200) {
                        $scope.record = result.data;
                        if(result.data.records.length>0){
                            $.ajax({
                                url : $scope.app.project_name+'/scenesPackage/getMediaSlotBeanList',
                                data : {'scenesId':result.data.records[0].id}
                            }).then(function(result) {
                                $scope.loading = false;
                                if (result.httpCode == 200) {
                                    $scope.showMedia = result.data.records;

                                } else {
                                    $scope.msg = result.msg;
                                }
                                $scope.$apply();
                            });
                        }
                    } else {
                        $scope.msg = result.msg;
                    }
                    $scope.$apply();
                });
            }
        }]);